package com.jandan.ui.client;

import java.util.Date;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.Margins;
import com.gwtext.client.core.Position;
import com.gwtext.client.core.RegionPosition;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.layout.BorderLayout;
import com.gwtext.client.widgets.layout.BorderLayoutData;
import com.jandan.ui.client.service.LessonService;
import com.jandan.ui.client.service.LessonServiceAsync;
import com.jandan.ui.client.service.StrangeWordService;
import com.jandan.ui.client.service.StrangeWordServiceAsync;
import com.jandan.ui.client.service.WordLibService;
import com.jandan.ui.client.service.WordLibServiceAsync;
import com.jandan.ui.client.util.ClientUtil;
import com.jandan.ui.model.LearnedData;
import com.jandan.ui.model.LearnedWord;
import com.jandan.ui.model.Lesson;
import com.jandan.ui.model.ReviewInfo;
import com.jandan.ui.model.StrangeWordGroupInfo;
import com.jandan.ui.model.Word;
import com.jandan.ui.model.WordLib;

public class WorkbenchPanel extends Panel implements ILessonOperator {
	private BannerPanel bannerPanel;
	private StudyPanel studyPanel;
	private LatestLearnedWordPanel latestLearnedWordPanel;
	private JandanArticlesPanel janDanArticlesPanel;
	private TabPanel centerTabPanel;
	private TabPanel rightTabPanel;

	private LeftPanel leftPanel;

	public WorkbenchPanel() {
		createComponent();
		this.setBorder(false);
	}

	private void createComponent() {
		this.setLayout(new BorderLayout());

		bannerPanel = new BannerPanel(this);
		bannerPanel.setHeight(130);

		this.add(bannerPanel, new BorderLayoutData(RegionPosition.NORTH));

		leftPanel = new LeftPanel(this);
		leftPanel.setWidth(250);

		BorderLayoutData leftPanelData = new BorderLayoutData(
				RegionPosition.WEST);
		leftPanelData.setSplit(true);
		leftPanelData.setMinSize(175);
		leftPanelData.setMaxSize(350);
		leftPanelData.setMargins(new Margins(0, 5, 0, 0));

		this.add(leftPanel, leftPanelData);

		centerTabPanel = new TabPanel();
		centerTabPanel.setDeferredRender(false);
		centerTabPanel.setTitle("中间面板");
		centerTabPanel.setResizeTabs(true);
		centerTabPanel.setTabPosition(Position.TOP);
		centerTabPanel.setMinTabWidth(95);
		centerTabPanel.setTabWidth(115);
		centerTabPanel.setEnableTabScroll(true);
		centerTabPanel.setActiveTab("study");
		centerTabPanel.setBorder(false);

		studyPanel = new StudyPanel(this);
		studyPanel.setId("study");
		studyPanel.setBorder(false);
		centerTabPanel.add(studyPanel);

		this.add(centerTabPanel, new BorderLayoutData(RegionPosition.CENTER));

		rightTabPanel = new TabPanel();
		rightTabPanel.setTitle("");
		// rightTabPanel.setTitleCollapse(true);
		rightTabPanel.setResizeTabs(true);
		rightTabPanel.setTabPosition(Position.BOTTOM);
		rightTabPanel.setMinTabWidth(95);
		rightTabPanel.setTabWidth(115);
		rightTabPanel.setEnableTabScroll(true);
		rightTabPanel.setActiveTab(0);
		rightTabPanel.setWidth(300);
		rightTabPanel.setBorder(false);
		// rightTabPanel.setClosable(true);
		rightTabPanel.setCollapsible(true);

		janDanArticlesPanel = new JandanArticlesPanel();
		janDanArticlesPanel.setBorder(false);
		janDanArticlesPanel.setId("jandan");
//		rightTabPanel.add(janDanArticlesPanel);

		latestLearnedWordPanel = new LatestLearnedWordPanel(this);
		latestLearnedWordPanel.setBorder(false);
		latestLearnedWordPanel.setId("latest");
		rightTabPanel.add(latestLearnedWordPanel);

		BorderLayoutData rightTabPanelData = new BorderLayoutData(
				RegionPosition.EAST);
		rightTabPanelData.setSplit(true);
		rightTabPanelData.setMinSize(175);
		rightTabPanelData.setMaxSize(350);
		rightTabPanelData.setMargins(new Margins(0, 5, 0, 0));

		this.add(rightTabPanel, rightTabPanelData);
	}

	public void addLesson(Lesson newLesson) {
		leftPanel.getMyLessonPanel().addLesson(newLesson);
	}

	public void deleteLesson(long lessonID) {
		// TODO Auto-generated method stub
		leftPanel.getMyLessonPanel().deleteLesson(lessonID);
	}

	public TreeMap<Long, String> getLessons() {
		// TODO Auto-generated method stub
		return leftPanel.getMyLessonPanel().getLessons();
	}

	public void study(long lessonID, int libNumber, final int studyStyle) {
		// TODO Auto-generated method stub
		// 判断时有课程正在被学习，如果有则提示是否关闭当前正在学习的课程
		// 如果没有的话
		Lesson currentLesson = studyPanel.getCurrentLesson();
		final int ln = libNumber;
		final long lid = lessonID;

		if (currentLesson != null) {
			long id = currentLesson.getLessonID();
			int n = studyPanel.getCurrentLibNumber();
			if (id == lessonID && n == ln) { // 当前课程，当前组
				centerTabPanel.activate(0);
				centerTabPanel.scrollToTab(studyPanel, true);
				// 功能面板要跳转到最近所学单词
				return;
			} else {
				// sb.append("是否关闭当前正在学习的课程?");
				MessageBox.confirm("提示", "是否关闭当前正在学习的课程?",
						new MessageBox.ConfirmCallback() {
							public void execute(String btnID) {
								// TODO Auto-generated method stub
								if (btnID.equals("yes")) {
									studyPanel.over();
									startStudy(lid, ln, studyStyle);
								}
							}
						});
			}
		} else {
			startStudy(lessonID, ln, studyStyle);
		}
	}

	public void studyStrangeWord(final int groupNumber) {
		// TODO Auto-generated method stub
		// 获取生词，并学习
//		MessageBox.alert("学习生词");
		// WordLibService wordLibService = WordLi
		if(groupNumber >= leftPanel.getStrangeWordPanel().getTotalGroupCount()){
			MessageBox.alert("没有可学习的生词组");
		}
		// 先判断是否正在学习这个生词本词库
		int studyStyle = studyPanel.getCurrentStudyStyle();
		if(studyStyle == ClientUtil.STUDY_STRANGE_WORD && studyPanel.getCurrentLibNumber() == groupNumber){
			return ;
		}
		
		// 如果不是正在学习此词库，再判断是否有学习其他的东西，如果有，则提示是否关闭
		if(studyPanel.getCurrentLesson() == null){
			startStudyStrangeWord(groupNumber);
			return ;
		}
		
		MessageBox.confirm("提示", "是否关闭当前正在学习的课程?",
				new MessageBox.ConfirmCallback() {
					public void execute(String btnID) {
						// TODO Auto-generated method stub
						if (btnID.equals("yes")) {
							studyPanel.over();
							startStudyStrangeWord(groupNumber);
						}
					}

				});		
	}
	
	private void startStudyStrangeWord(final int groupNumber) {
		// TODO Auto-generated method stub
		StrangeWordServiceAsync strangeWordService = StrangeWordService.Util.getInstance();
		strangeWordService.getNewStrangeWordAndLearnedStrangeWordList(groupNumber, new AsyncCallback<Map<String,List>>(){

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				MessageBox.alert("获取要学习的生词错误!");
			}

			public void onSuccess(Map<String, List> map) {
				// TODO Auto-generated method stub
				if(map != null){
					centerTabPanel.setActiveItem(0);
					studyPanel.setStudyStyle(ClientUtil.STUDY_STRANGE_WORD);
					
					Lesson lesson = new Lesson();
					lesson.setLessonID(ClientUtil.STRANGE_LESSON_ID);
					lesson.setLessonName("生词本");
					lesson.setNewWordsCountOfPerTurn(10);
					studyPanel.setCurrentLesson(lesson);
					studyPanel.setNewWordList(map.get("newStrangeWordList"));
					studyPanel.addToLearnedWordMap(map
							.get("learnedStrangeWordList"));
					studyPanel.study();
				}
			}
		});
	}

	public void checkLib(WordLib wordLib) {
		// TODO Auto-generated method stub
		Component[] cs = centerTabPanel.getItems();
		Panel tab = null;
		String tabId = null;
		for (int i = 0; i < cs.length; i++) {
			tab = (Panel) cs[i];
			tabId = tab.getId();
			System.out.println("tabId:" + tabId);
			if (tabId.equals("wordlib_" + wordLib.getWordLibID())) {
				centerTabPanel.activate(tabId);
				centerTabPanel.scrollToTab(tab, true);
				return;
			}
		}

		tab = new BrowseWordLibGridPanel(wordLib.getWordLibID());
		tab.setAutoScroll(true);
		tab.setTitle(wordLib.getWordLibName());
		tab.setId("wordlib_" + wordLib.getWordLibID());
		tab.setClosable(true);

		// MessageBox.alert(wordLib.getWordLibName());

		centerTabPanel.add(tab);
		centerTabPanel.activate(tab.getId());
		centerTabPanel.scrollToTab(tab, true);
	}

	public void studyNextLesson(long lessonID, int currentlibNumber) {
		int libNumber = ++currentlibNumber;
		int ss = ClientUtil.STUDY_NEW_WORD;

		startStudy(lessonID, libNumber, ss);
	}

	public void studyNextWordLib(long lessonID, int n, int studyStyle) {
		startStudy(lessonID, n, studyStyle);
	}

	private void startStudy(long lessonID, int n, final int studyStyle) {
		final LessonServiceAsync lessonService = LessonService.Util.getInstance();
		final int libNumber = n;

		lessonService.getLesson(lessonID, new AsyncCallback<Lesson>() {
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
			}

			public void onSuccess(Lesson lesson) {
				// TODO Auto-generated method stub
				// 判断libnumber是否合法
				// 此词库没有可学习的单词，请学习其他课程

				if (lesson != null) {
					// rightTabPanel.activate(2);
					// rightTabPanel.setActiveItemID("latest");
					rightTabPanel.activate("latest");
					studyPanel.setCurrentLesson(lesson);
					lesson.setLatestLearnedDate(new Date());
					
					lessonService.updateLesson(lesson,new AsyncCallback() {

						public void onFailure(Throwable arg0) {
							// TODO Auto-generated method stub
							MessageBox.alert("更新课程信息错误！");
						}

						public void onSuccess(Object arg0) {
							// TODO Auto-generated method stub
							
						}
						
					});
					
					if (studyStyle == ClientUtil.STUDY_NEW_WORD) {

						// 获取要学习的单词
						studyPanel.setStudyStyle(studyStyle);
						studyPanel.setCurrentLibNumber(libNumber);
						startLearnNewWord(lesson.getLessonID(), libNumber);
					}
				}
			}
		});
	}

	private void startLearnNewWord(long lessonID, int libNumber) {
		LessonServiceAsync lessonService = LessonService.Util.getInstance();

		lessonService.getNewWordAndLearnedWordListByLessonID(lessonID,
				libNumber, new AsyncCallback<Map<String, List>>() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						MessageBox.alert("获取要学习的新单词错误!");
					}

					public void onSuccess(Map<String, List> map) {
						// TODO Auto-generated method stub
						centerTabPanel.setActiveItem(0);

						studyPanel.setNewWordList(map.get("newWordList"));
						studyPanel.addToLearnedWordMap(map
								.get("learnedWordList"));
						studyPanel.study();
					}
				});
	}

	public void addLatestLearnedWord(LearnedWord learnedWord) {
		// TODO Auto-generated method stub
		latestLearnedWordPanel.addLatestLearnedWord(learnedWord);
	}

	public void browseStrangeWord() {
		// TODO Auto-generated method stub
		Component[] cs = centerTabPanel.getItems();
		Panel tab = null;
		String tabId = null;
		for (int i = 0; i < cs.length; i++) {
			tab = (Panel) cs[i];
			tabId = tab.getId();
			// System.out.println("tabId:" + tabId);
			if (tabId.equals("nb")) {
				centerTabPanel.activate(tabId);
				centerTabPanel.scrollToTab(tab, true);
				return;
			}
		}

		tab = new BrowseStrangeWordGridPanel();
		tab.setAutoScroll(true);
		tab.setTitle("查看生词本");
		tab.setId("nb");
		tab.setClosable(true);

		centerTabPanel.add(tab);
		centerTabPanel.activate(tab.getId());
		centerTabPanel.scrollToTab(tab, true);
	}

	public void browseLearnedWord(long lessonID, int libNumber) {
		// TODO Auto-generated method stub
		Component[] cs = centerTabPanel.getItems();
		Panel tab = null;
		String tabId = null;
		for (int i = 0; i < cs.length; i++) {
			tab = (Panel) cs[i];
			tabId = tab.getId();
			// System.out.println("tabId:" + tabId);
			if (tabId.equals("br_lesson_" + lessonID + "_" + libNumber)) {
				centerTabPanel.activate(tabId);
				centerTabPanel.scrollToTab(tab, true);
				return;
			}
		}

		tab = new BrowseLearnedWordGridPanel(lessonID, libNumber);
		tab.setAutoScroll(true);
		tab.setTitle("浏览已学单词");
		tab.setId("br_lesson_" + lessonID + "_" + libNumber);
		tab.setClosable(true);

		centerTabPanel.add(tab);
		centerTabPanel.activate(tab.getId());
		centerTabPanel.scrollToTab(tab, true);
	}

	public void displayWordInfo(Word word) {
		// TODO Auto-generated method stub
		Component[] cs = centerTabPanel.getItems();

		Panel tab = null;
		String tabId = null;
		for (int i = 0; i < cs.length; i++) {
			tab = (Panel) cs[i];
			tabId = tab.getId();
			// System.out.println("tabId:" + tabId);
			if (tabId.equals("br_word_" + word.getWordID())) {
				centerTabPanel.activate(tabId);
				centerTabPanel.scrollToTab(tab, true);
				return;
			}
		}

		tab = new WordPanel(word);
		tab.setAutoScroll(true);
		tab.setTitle(word.getWordEn());
		tab.setId("br_word_" + word.getWordID());
		tab.setClosable(true);

		centerTabPanel.add(tab);
		centerTabPanel.activate(tab.getId());
		centerTabPanel.scrollToTab(tab, true);
	}

	public void addStrangeWord() {
		// TODO Auto-generated method stub
		Panel tab = new AddStrangeWordPanel(this);
		tab.setAutoScroll(true);
		tab.setTitle("添加生词");
		// tab.setId("br_word_" + word.getWordID());
		tab.setClosable(true);

		centerTabPanel.add(tab);
		centerTabPanel.activate(tab.getId());
		centerTabPanel.scrollToTab(tab, true);
	}

	public void closeStrangePanel(String tabId) {
		// TODO Auto-generated method stub
		centerTabPanel.remove(tabId);
	}

	public void displayLessonInfo(final Lesson lesson) {
		// TODO Auto-generated method stub
		Component[] cs = centerTabPanel.getItems();
		Panel tab = null;
		String tabId = null;
		for (int i = 0; i < cs.length; i++) {
			tab = (Panel) cs[i];
			tabId = tab.getId();
			// System.out.println("tabId:" + tabId);
			if (tabId.equals("br_lesson_" + lesson.getLessonID())) {
				centerTabPanel.activate(tabId);
				centerTabPanel.scrollToTab(tab, true);
				return;
			}
		}
		//获取学习数据
		final LessonServiceAsync lessonService = LessonService.Util.getInstance();
		
		lessonService.getLearnedData(lesson.getLessonID(),new AsyncCallback<LearnedData>(){
			public void onFailure(Throwable arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onSuccess(final LearnedData learnedData) {
				// TODO Auto-generated method stub
				// 获取复习信息和
				lessonService.getReviewInfoList(lesson.getLessonID(),
						new AsyncCallback<List<ReviewInfo>>() {

							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub
								MessageBox.alert("获取当天学习的单词数据错误");
							}

							public void onSuccess(List<ReviewInfo> result) {
								// TODO Auto-generated method stub
//								MessageBox.alert("获取数据成功");
								//						
								StatisticsInfoPanel tab;// = new
								// StatisticsInfoPanel(lesson);
								if (result != null && result.size() > 0) {
									tab = new StatisticsInfoPanel(lesson,learnedData,result);
									setLessonOperator(tab);
								} else {
									tab = new StatisticsInfoPanel(lesson);
								}
								tab.setId("br_lesson_" + lesson.getLessonID());

								// tab.setId("br_word_" + word.getWordID());
								tab.setClosable(true);

								centerTabPanel.add(tab);
								centerTabPanel.activate(tab.getId());
								centerTabPanel.scrollToTab(tab, true);
							}
						});

			}
		});
	}

	public void displayAllWordLib() {
		// TODO Auto-generated method stub
		Component[] cs = centerTabPanel.getItems();
		Panel tab = null;
		String tabId = null;
		for (int i = 0; i < cs.length; i++) {
			tab = (Panel) cs[i];
			tabId = tab.getId();
			// System.out.println("tabId:" + tabId);
			if (tabId.equals("br_all_word_libs")) {
				centerTabPanel.activate(tabId);
				centerTabPanel.scrollToTab(tab, true);
				return;
			}
		}

		WordLibServiceAsync wordLibService = WordLibService.Util.getInstance();
		wordLibService.getWordLibList(new AsyncCallback<List<WordLib>>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				MessageBox.alert("获取词库信息错误");
			}

			public void onSuccess(List<WordLib> wordLibList) {
				// TODO Auto-generated method stub
				DisplayAllLibPanel tab = new DisplayAllLibPanel(wordLibList);
				setDisplayOperator(tab);
				tab.setId("br_all_word_libs");
				// tab.setId("br_word_" + word.getWordID());
				tab.setClosable(true);

				centerTabPanel.add(tab);
				centerTabPanel.activate(tab.getId());
				centerTabPanel.scrollToTab(tab, true);
			}
		});

	}

	public void reviewTodayLearnedWords(final Lesson lesson) {
		// TODO Auto-generated method stub
		// MessageBox.alert("复习");
		if (studyPanel.getCurrentLesson() == null) {
			startReviewTodayLearnedWords(lesson);
			return;
		}
		MessageBox.confirm("提示", "是否关闭当前正在学习的课程?",
				new MessageBox.ConfirmCallback() {
					public void execute(String btnID) {
						// TODO Auto-generated method stub
						if (btnID.equals("yes")) {
							studyPanel.over();
							startReviewTodayLearnedWords(lesson);
						}
					}
				});
	}

	private void startReviewTodayLearnedWords(final Lesson lesson){
		final LessonServiceAsync lessonService = LessonService.Util.getInstance();
		lessonService.getTodayReviewLearnedWordList(lesson.getLessonID(),
				new AsyncCallback<List<LearnedWord>>() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						MessageBox.alert(caught.getMessage());
					}

					public void onSuccess(List<LearnedWord> result) {
						// TODO Auto-generated method stub
						if (result != null && result.size() > 0) {
							lesson.setLatestLearnedDate(new Date());
							lessonService.updateLesson(lesson, new AsyncCallback(){

								public void onFailure(Throwable arg0) {
									// TODO Auto-generated method stub
									MessageBox.alert("更新课程信息错误！");
								}

								public void onSuccess(Object arg0) {
									// TODO Auto-generated method stub
									
								}
								
							});
							
							centerTabPanel.setActiveItem(0);
							rightTabPanel.activate("latest");
							studyPanel.setCurrentLesson(lesson);
							studyPanel
									.setStudyStyle(ClientUtil.REVIEW_OLD_WORD);
							studyPanel.addToLearnedWordMap(result);
							studyPanel.study();
						}
					}
				});
	}
	

	public void reviewLearnedWords(final Lesson lesson,final List<Date> dateList) {
		// TODO Auto-generated method stub
		if (studyPanel.getCurrentLesson() == null) {
			startReviewLearnedWords(lesson,dateList);
			return;
		}
		MessageBox.confirm("提示", "是否关闭当前正在学习的课程?",
				new MessageBox.ConfirmCallback() {
					public void execute(String btnID) {
						// TODO Auto-generated method stub
						if (btnID.equals("yes")) {
							studyPanel.over();
							startReviewLearnedWords(lesson,dateList);
						}
					}
				});
	}

	private void startReviewLearnedWords(final Lesson lesson,final List<Date> dateList) {
		// TODO Auto-generated method stub
		final LessonServiceAsync lessonService = LessonService.Util.getInstance();
		lessonService.getReviewLearnedWordList(lesson.getLessonID(),dateList,
				new AsyncCallback<List<LearnedWord>>() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						MessageBox.alert(caught.getMessage());
					}

					public void onSuccess(List<LearnedWord> result) {
						// TODO Auto-generated method stub
						if (result != null && result.size() > 0) {
							lesson.setLatestLearnedDate(new Date());
							lessonService.updateLesson(lesson, new AsyncCallback(){

								public void onFailure(Throwable arg0) {
									// TODO Auto-generated method stub
									MessageBox.alert("更新课程信息错误！");
								}

								public void onSuccess(Object arg0) {
									// TODO Auto-generated method stub
									
								}
								
							});
							
							centerTabPanel.setActiveItem(0);
							rightTabPanel.activate("latest");
							studyPanel.setCurrentLesson(lesson);
							studyPanel
									.setStudyStyle(ClientUtil.REVIEW_OLD_WORD);
							studyPanel.addToLearnedWordMap(result);
							studyPanel.study();
						}
					}
				});		
	}

	private void setLessonOperator(StatisticsInfoPanel panel) {
		panel.setLessonOperator(this);
	}
	
//	private void setDisplayAllLibPanelOperator(DisplayAllLibPanel pan)
	private void setDisplayOperator(DisplayAllLibPanel panel){
		panel.setLessonOperator(this);
	}

	public void refeshStrangeWordPanel() {
		// TODO Auto-generated method stub
		//获取生词本分组信息，重新生成节点
		StrangeWordServiceAsync strangeWordService = StrangeWordService.Util.getInstance();
		strangeWordService
		.getStrangeWordGroupInfoList(new AsyncCallback<List<StrangeWordGroupInfo>>() {

			public void onFailure(Throwable t) {
				// TODO Auto-generated method stub
				System.out.println(t.getMessage());
			}

			public void onSuccess(
					List<StrangeWordGroupInfo> strangeWordGroupInfoList) {
				// TODO Auto-generated method stub
				if (strangeWordGroupInfoList != null
						&& strangeWordGroupInfoList.size() > 0) {
					leftPanel.getStrangeWordPanel().refresh(strangeWordGroupInfoList);
				}
			}
		});
	}

}
